# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     pdf_to_image             |
|Author:        WYT                      |
|date:          2020/6/8                 |
 ----------------------------------------
|  Change Activity:                      |
|                   2020/6/8:            |
-----------------------------------------
"""
import platform
from glob import glob

import fitz
import os

from PIL import Image
from pdf2image import convert_from_path

from settings import base_path


def pyMuPDF_fitz(imagePath, num=2.4, filename="", filePath=None):
    page = None
    if filePath:
        pdfDoc = fitz.open(filePath)
        page = None if len(pdfDoc) <= 0 else pdfDoc[0]
    if not filePath and page is None:
        return False
        # pdfDoc = fitz.open(pdfPath)
        # if startPage != endPage:
        #     return False
        # page = pdfDoc[startPage - 1]
    rotate = int(0)
    # 每个尺寸的缩放系数为1.3，这将为我们生成分辨率提高2.6的图像。
    # 此处若是不做设置，默认图片大小为：792X612, dpi=96
    zoom_x = num
    zoom_y = num
    mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
    pix = page.getPixmap(matrix=mat, alpha=0)

    if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在
        os.makedirs(imagePath)  # 若图片文件夹不存在就创建

    # pix.writePNG(imagePath + '/' + 'images_%s.png' % pg)  # 将图片写入指定的文件夹内
    file_path = imagePath + '/' + filename + ".png"
    pix.writePNG(file_path)  # 将图片写入指定的文件夹内
    return file_path


def get_FileSize(filePath):
    fsize = os.path.getsize(filePath)
    fsize = fsize / float(1024 * 1024)
    a = round(fsize, 2)
    return a


def pdf_to_image(imagePath, filename, num=2.4, size=0.48, filePath=None):
    while True:
        file_path = pyMuPDF_fitz(imagePath=imagePath, num=num,
                                 filename=filename, filePath=filePath)
        if file_path is False:
            return ""
        file_size = get_FileSize(file_path)
        num -= 0.1
        if file_size <= size:
            return file_path
            break

def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024

def get_outfile(infile, outfile):
    if outfile:
        return outfile
    dir, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dir, suffix)
    return outfile

def compress_image(infile, outfile='', mb=150, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """
    o_size = get_size(infile)
    if o_size <= mb:
        return infile
    outfile = get_outfile(infile, outfile)
    while o_size > mb:
        im = Image.open(infile)
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)
    return outfile, get_size(outfile)

def img_pdfs(self, path='', img_list=[]):
    """把图片转换成pdf
    f_size: int, 压缩目标，KB
    quality: int, 初始压缩比率
    """
    img_path = '/'.join(path.replace('\\', '/').split('/')[0:-1])
    # path = path.replace('\\', '/').replace('.pdf', '_1.pdf')
    path = path.replace('\\', '/')
    doc = fitz.open()
    images = glob(img_path + f'//*.png')
    buslic = "{}\\buslic.png".format(self.save_path.replace("\\", "/"))
    if buslic in images:
        images.remove("{}\\buslic.png".format(self.save_path.replace("\\", "/")))
    image_list = [i.replace(img_path, "").replace("\\", "") for i in images]
    if img_list:
        image_list = img_list
    # image_list.sort(key=lambda x: int(x.split("_")[0]))
    for img in image_list:
        img = img_path + '/' + img
        imgpdf = fitz.open('pdf', fitz.open(img).convertToPDF())
        doc.insertPDF(imgpdf)  # 将当前页插入pdf文档
        os.remove(img)
    doc.save(path)  # 保存pdf文件
    doc.close()
    return path

def compress(infile, outfile, size=0.5):
    if os.path.isfile(outfile):
        if int(os.path.getsize(outfile)) < int(size):
            return
    mb = 1920
    poppler_path = "{}\\poppler\\Library\\bin".format(base_path)
    system = platform.system()
    if system == "Linux":
        poppler_path = None
    pdf_path = infile.replace("\\", "/")
    basePath = pdf_path.replace(pdf_path.split("/")[-1], "")
    while True:
        pages = convert_from_path(
            pdf_path=pdf_path,
            thread_count=50,
            poppler_path=poppler_path,
            size=(mb, None)
        )
        res_path = outfile.replace(".png", "_res.png")
        pages[0].save(outfile.replace(".png", "_res.png"))
        if os.path.getsize(res_path) < size * 1024 * 1024:
            return





if __name__ == '__main__':
    data_path = "{}\\test\\data".format(base_path)
    if not os.path.exists(data_path):
        os.makedirs(data_path)
    # pdf_to_image(imagePath=data_path, filename="buslic", filePath=data_path + "\\buslic.pdf")
    # compress_image(infile=data_path + "\\buslic.jpg", outfile=data_path + "\\buslic_c.jpg", mb=500)
    pass
# "常州市三维技术成套设备有限公司",
# "江苏东方龙机车集团有限公司",
# "常州天兴环保科技有限公司",
# "常州市步步干燥设备有限公司",
# "常州海登赛思涂装设备有限公司",
# "常州市新未来化工有限公司",
# "常州盛天传动科技有限公司",
# "常州科沛达清洗技术股份有限公司 ",
# "常州银山铸造有限公司",
# "常州钜苓铸造有限公司",
# "常州润达铁合金有限公司",
# "常州市雷利压力控制器有限公司",
# "迪恩医疗科技有限公司",
# "常州市武进晶丰电子有限公司",
# "江苏曼威德电气有限公司",
# "常州亿盛电子电器有限公司",
# "常州世卓精密锻造有限公司",
# "常州联能机械有限公司",
# "常州金奇雕数控机床有限公司",
# "常州杰仕特网印机械有限公司",
# "江苏优特安智能科技公司",
# "常州市震华干燥设备有限公司",
# "常州市莱欧铸造有限公司",
# "常州市信合久塑料有限公司"
